package com.sun.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.common.Result;
import com.sun.common.SystemCrmlog;
import com.sun.entity.QuartzBean;
import com.sun.service.QuartzService;
import com.sun.utils.CronUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Project: hospitalDrugInformationManagement
 * @Author: 86178
 * @Date: 2023/3/29 15:09
 * @FileName: QuartzController
 * @Description: ""
 */
@Slf4j
@RestController
@RequestMapping("/quartz")
public class QuartzController {

    @Autowired
    private QuartzService quartzService;

    /**
     * 查询定时任务列表
     */
    @GetMapping("/list")
    public Result<Page> list(int pageNum, int pageSize, String jobName, String jobGroup, String status) {
        Page<QuartzBean> pageInfo = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<QuartzBean> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(jobName), QuartzBean::getJobName, jobName);
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(jobGroup), QuartzBean::getJobGroup, jobGroup);
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(status), QuartzBean::getStatus, status);
        quartzService.page(pageInfo, lambdaQueryWrapper);
        return Result.success(pageInfo);
    }

    /**
     * 查询库存管理的定时任务列表
     */
    @GetMapping("/listStore")
    public Result<Page> listStore(int pageNum, int pageSize, String jobName, String jobGroup, String status) {
        Page<QuartzBean> pageInfo = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<QuartzBean> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(jobName), QuartzBean::getJobName, jobName);
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(jobGroup), QuartzBean::getJobGroup, jobGroup);
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(status), QuartzBean::getStatus, status);
        lambdaQueryWrapper.eq(QuartzBean::getJobGroup, "库存");
        quartzService.page(pageInfo, lambdaQueryWrapper);
        return Result.success(pageInfo);
    }

    /**
     * 获取定时任务详细信息
     */
    @GetMapping(value = "/{jobId}")
    public Result<QuartzBean> getInfo(@PathVariable("jobId") Long jobId) {
        QuartzBean quartzBean = quartzService.getById(jobId);
        Date next = CronUtils.getNextExecution(quartzBean.getCronExpression());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:s");
        String s = simpleDateFormat.format(next);
        quartzBean.setNextValidTime(s);
        return Result.success(quartzBean);
    }

    /**
     * 新增定时任务
     */
    @SystemCrmlog(title = "系统管理模块", type = "INSERT", description = "新增定时任务")
    @PostMapping
    public Result<String> createJob(@RequestBody QuartzBean quartzBean) {
        if (!CronUtils.isValid(quartzBean.getCronExpression())) {
            return Result.error("新增任务'" + quartzBean.getJobName() + "'失败，Cron表达式不正确");
        }
        int save = quartzService.insertJob(quartzBean);
        if (save != 0) {
            return Result.success("新增任务成功");
        } else {
            return Result.error("新增任务失败");
        }
    }

    /**
     * 定时任务状态修改
     */
    @SystemCrmlog(title = "系统管理模块", type = "UPDATE", description = "定时任务状态修改")
    @PutMapping("/changeStatus")
    public Result<String> changeStatus(@RequestBody QuartzBean job) {
        QuartzBean newJob = quartzService.getById(job.getJobId());
        newJob.setStatus(job.getStatus());
        int i = 0;
        try {
            i = quartzService.changeStatus(newJob);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        if (i > 0) {
            return Result.success("状态修改成功");
        }
        return Result.error("状态修改失败");
    }


    /**
     * 定时任务立即执行一次
     */
    @SystemCrmlog(title = "系统管理模块", type = "UPDATE", description = "定时任务立即执行一次")
    @PutMapping("/run")
    public Result<String> run(@RequestBody QuartzBean job) {
        boolean result = false;
        try {
            result = quartzService.run(job);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return result ? Result.success("成功") : Result.error("任务不存在或已过期！");
    }

    /**
     * 删除定时任务
     */
    @SystemCrmlog(title = "系统管理模块", type = "DELETE", description = "删除定时任务")
    @DeleteMapping("/{jobIds}")
    public Result remove(@PathVariable Long[] jobIds) {
        try {
            quartzService.deleteJobByIds(jobIds);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return Result.success("删除成功");
    }


    /**
     * 修改定时任务
     */
    @SystemCrmlog(title = "系统管理模块", type = "UPDATE", description = "修改定时任务")
    @PutMapping
    public Result<String> update(@RequestBody QuartzBean quartzBean) {
        log.info(String.valueOf(quartzBean));
        if (!CronUtils.isValid(quartzBean.getCronExpression())) {
            return Result.error("修改任务'" + quartzBean.getJobName() + "'失败，Cron表达式不正确");
        }
        int row = quartzService.updateJob(quartzBean);
        if (row != 0) {
            return Result.success("修改任务成功");
        } else {
            return Result.error("修改任务失败");
        }
    }
}
